//
//  ImageSelect.m
//  jz_sanrenxing
//
//  Created by Killua on 2016/10/6.
//  Copyright © 2016年 杭州景忠网络科技有限公司. All rights reserved.
//

#import "ImageSelectManager.h"
#import "AppDelegate.h"
#import <AVFoundation/AVFoundation.h>

@interface ImageSelectManager()<UIImagePickerControllerDelegate,UINavigationControllerDelegate>{

}
@end

@implementation ImageSelectManager

#pragma mark 从用户相册获取活动图片
- (void)pickImageFromAlbum:(BOOL)editing {
    UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
    imagePicker.delegate = self;
    imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    imagePicker.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
    imagePicker.allowsEditing = editing;
    AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    NSLog(@"presentViewController:%@,%@,%@",appDelegate.window.rootViewController,appDelegate.window.rootViewController.presentedViewController,appDelegate.window.rootViewController.presentingViewController);
    UIViewController *presentedCtr=appDelegate.window.rootViewController;
    if (!presentedCtr) {
        presentedCtr=appDelegate.window.rootViewController;
    }
    [presentedCtr presentViewController:imagePicker animated:YES completion:nil];
}

#pragma mark 从摄像头获取活动图片
- (void)pickImageFromCamera:(BOOL)editing {
    if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]){

        UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
        imagePicker.delegate = self;
        imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
        imagePicker.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
        imagePicker.allowsEditing = editing;
        AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;

        NSLog(@"presentViewController:%@",appDelegate.window.rootViewController.presentedViewController);
        UIViewController *presentedCtr=appDelegate.window.rootViewController.presentedViewController;
        if (!presentedCtr) {
            presentedCtr=appDelegate.window.rootViewController;
        }
        [presentedCtr presentViewController:imagePicker animated:YES completion:nil];
    }
}

#pragma mark 从用户相册获取视频
- (void)pickVideoFromAlbum:(BOOL)editing {
    UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
    imagePicker.delegate = self;
    
    imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    imagePicker.allowsEditing = editing;
//    imagePicker.videoMaximumDuration = 300.0f;//设置最长录制5分钟
    imagePicker.mediaTypes = [NSArray arrayWithObject:@"public.movie"];

    AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    NSLog(@"presentViewController:%@,%@,%@",appDelegate.window.rootViewController,appDelegate.window.rootViewController.presentedViewController,appDelegate.window.rootViewController.presentingViewController);
    
    UIViewController *presentedCtr=appDelegate.window.rootViewController;
    if (!presentedCtr) {
        presentedCtr=appDelegate.window.rootViewController;
    }
    [presentedCtr presentViewController:imagePicker animated:YES completion:nil];
    
}


- (void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    NSLog(@"%@",info);

    UIImage *image;
    NSString *videoString;
    //上传图片
    if ([info objectForKey:@"UIImagePickerControllerEditedImage"] || [info objectForKey:@"UIImagePickerControllerOriginalImage"]) {
        if(picker.allowsEditing)
            image = [info objectForKey:@"UIImagePickerControllerEditedImage"];
        else
            image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
        
        
        //将拍照图片存入手机相册
        if (picker.sourceType == UIImagePickerControllerSourceTypeCamera) {
            UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
        }
        videoString = nil;
        
   //上传视频
    }else{
        
        NSURL *sourceURL;
        if ([info objectForKey:UIImagePickerControllerMediaURL]) {
            sourceURL = [info objectForKey:UIImagePickerControllerMediaURL];
        }
        videoString = [NSString stringWithFormat:@"%@",sourceURL];
        //获取视频第一帧图片
        image = [self thumbnailImageForVideo:sourceURL atTime:1.0];

        
    }
    
    
    
    if([self.delegate respondsToSelector:@selector(selectedImage: FullPath: VideoPath:)]) {
        
        [self saveImage:image WithName:@"image"];
        [self.delegate selectedImage:image FullPath:_fullPath VideoPath:videoString];
        
    }

    AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;

    UIViewController *presentedCtr=appDelegate.window.rootViewController.presentedViewController;
    if (!presentedCtr) {
        presentedCtr=appDelegate.window.rootViewController;
    }
    [presentedCtr dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark 保存图片到document
- (void)saveImage:(UIImage *)tempImage WithName:(NSString *)imageName {
    NSData *imageData = UIImageJPEGRepresentation(tempImage, 0.6);
    NSString* fullPathToFile = [[self documentFolderPath] stringByAppendingPathComponent:imageName];
    _fullPath = fullPathToFile;
    [imageData writeToFile:fullPathToFile atomically:NO];
}
- (NSString *)documentFolderPath {
    return [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
}
- (UIImage*)imageWithImageSimple:(UIImage*)image scaledToSize:(CGSize)newSize {
    // Create a graphics image context
    UIGraphicsBeginImageContext(newSize);

    // Tell the old image to draw in this new context, with the desired
    // new size
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];

    // Get the new image from the context
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();

    // End the context
    UIGraphicsEndImageContext();

    // Return the new image.
    return newImage;
}

//获取视频第一帧图片
- (UIImage*) thumbnailImageForVideo:(NSURL *)videoURL atTime:(NSTimeInterval)time {
    AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:videoURL options:nil];
    NSParameterAssert(asset);
    AVAssetImageGenerator *assetImageGenerator = [[AVAssetImageGenerator alloc] initWithAsset:asset];
    assetImageGenerator.appliesPreferredTrackTransform = YES;
    assetImageGenerator.apertureMode = AVAssetImageGeneratorApertureModeEncodedPixels;
    
    CGImageRef thumbnailImageRef = NULL;
    CFTimeInterval thumbnailImageTime = time;
    NSError *thumbnailImageGenerationError = nil;
    thumbnailImageRef = [assetImageGenerator copyCGImageAtTime:CMTimeMake(thumbnailImageTime, 60) actualTime:NULL error:&thumbnailImageGenerationError];
    
    if (!thumbnailImageRef)
        NSLog(@"thumbnailImageGenerationError %@", thumbnailImageGenerationError);
    
    UIImage *thumbnailImage = thumbnailImageRef ? [[UIImage alloc] initWithCGImage:thumbnailImageRef] : nil;
    
    return thumbnailImage;
}


@end
